<template>
  <ComDialog v-model="dialogVisible"
   :width="dialogWidth"
  :title="id ? '编辑' : '新增'">
    <ElementEasyForm ref="comFromRef" :formJson="formJson">

      <template #deptId>
        <el-cascader
                class="w100"
                :options="state.deptOptions"
                v-model="formJson.model.deptId"
                :props="{
               value: 'id',
                    emitPath: false,
            checkStrictly: true,
                }"
                clearable
              />
      </template>
      <template #postIds>
              <el-select
                class="w100"
                v-model="formJson.model.postIds"
                multiple
                placeholder="请选择岗位"
              >
                <el-option
                  v-for="item in state.postOptions"
                  :key="item.postId"
                  :label="item.postName"
                  :value="item.postId"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
      </template>
      <template #roleIds>
       
              <el-select
                class="w100"
                v-model="formJson.model.roleIds"
                multiple
                placeholder="请选择角色"
              >
              <el-option
                  v-for="item in state.roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
      </template>
    </ElementEasyForm>
    <template #footer>
	<div >
			<el-button size="large" @click="handleClose">取消</el-button>
			<el-button size="large" :loading="subLoading" type="primary" @click="submitData">保存</el-button>
		</div>
    </template>
    	
  </ComDialog>
</template>

<script setup lang="tsx">
import { ref, reactive, defineEmits, onMounted, watch, shallowRef } from "vue";

import {
  getUser,
  addUser,
  updateUser,
  deptTreeSelect,
} from "/@ts/axios/urlApi/system/user";
import { dialogWidth } from "/@ts/enums/sizeEnum";
import { ElMessage } from "element-plus";
import { itemValue } from "/@ts/hooks/format";
import { hidden } from "element-easy-form/dist/drag-form/tool";
import { getConfigKey } from "/@ts/axios/urlApi/system/config";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const emit = defineEmits(["update:modelValue","update"]);
const dialogVisible = shallowRef(false);
const subLoading = shallowRef(false);
const comFromRef = ref<any>();

const submitData = async () => {
  try {
    const res = await comFromRef.value.validate();
    if (props.id) {
      updateUser(res).then((resItem: any) => {
        ElMessage.success(t("操作成功"));
        handleClose();
        emit("update");
      });
    } else {
      addUser(res).then((resItem: any) => {
        ElMessage.success(t("操作成功"));
        handleClose();
        emit("update");
      });
    }
  } catch (error) {
    console.log("error :>> ", error);
  }
};
const state = reactive({
  deptOptions:[],
  postOptions:[],
  roleOptions:[],
  initPassword:""
});
const formJson = ref<any>({
  schema: [
    {
      label: "用户昵称",
      prop: "nickName",
      colAttrs: {
        span: 12,
      },
      componentName: "ElInput",
      attrs: {
        placeholder: "请输入名字",
      },
      rules: [{ required: true, message: "不能为空", trigger: 'change', }],
    },
      {
      label: "归属部门",
      prop: "deptId",
      colAttrs: {
        span: 12,
      },
      componentName: "ElDatePicker",
      attrs: {
        placeholder: "请选择",
      },
      rules: [{ required: false, message: "不能为空", trigger: 'change', }],
    },
       {
      label: "手机号码",
      prop: "phonenumber",
      colAttrs: {
        span: 12,
      },
      componentName: "ElInput",
      rules: [ {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的手机号码",
        trigger: "blur",
      }],
      attrs: {
        type: "number",
        placeholder: "请选择",
      },
    
    },
    {
      label: "邮箱",
      prop: "email",
      colAttrs: {
        span: 12,
      },
      componentName: "ElInput",
      rules: [ {
        type: "email",
        message: "请输入正确的邮箱地址",
        trigger: ["blur", "change"],
      }],
      attrs: {
       
        placeholder: "请选择",
      },
    
    },
    {
      label: "用户名称",
      prop: "userName",
      colAttrs: {
        span: 12,
      },
      rules: [{ required: true, message: "不能为空", trigger: 'change', }],
      componentName: "ElInput",
      hidden:{
         "matchPattern": "&&",
         "dataSelect":[],
        "type": "function",
        value:false,
        dataJs:(config,data)=>{
        return data.userId != undefined
      }
      },
      attrs: {
      
        placeholder: "请输入",
      },
    
    },
    {
      label: "用户密码",
      prop: "password",
      colAttrs: {
        span: 12,
        
      },
      rules:  [
      { required: true, message: "用户密码不能为空", trigger: "blur" },
      {
        min: 5,
        max: 20,
        message: "用户密码长度必须介于 5 和 20 之间",
        trigger: "blur",
      },
    ],
      componentName: "ElInput",
        hidden:{
         "matchPattern": "&&",
         "dataSelect":[],
        "type": "function",
        value:false,
        dataJs:(config,data)=>{
        return data.userId != undefined
      }
      },
      attrs: {
        maxlength: "20",
        placeholder: "请输入",
        showPassword: true,
      },
    
    },
    {
      label: "性别",
      prop: "sex",
      colAttrs: {
        span: 12,
        
      },
      componentName: "selectDict",
      attrs: {
        dictCode: "sys_user_sex",
        placeholder: "请选择",
        showPassword: true,
      },
    
    },
    {
      label: "状态",
      prop: "status",
      colAttrs: {
        span: 12,
        
      },
      componentName: "selectDict",
      attrs: {
        dictCode: "sys_normal_disable",
        placeholder: "请选择",
        showPassword: true,
      },
    
    },
    {
      label: "岗位",
      prop: "postIds",
      colAttrs: {
        span: 12,
        
      },
      componentName: "ElInput",
      attrs: {
      
      },
    
    },
    {
      label: "角色",
      prop: "roleIds",
      colAttrs: {
        span: 12,
        
      },
      componentName: "ElInput",
      attrs: {
      
      },
    
    },
   
    {
      label: "备注",
      type: "COMPONENT",
      formItemAttrs: {},
      attrs: {
        placeholder: "请输入",
        type: "textarea",
      },
      rules: [],
      prop: "remark",
      componentName: "ElInput",
      colAttrs: {
        span: 24,
      },
    },
  ],
 "rowAttrs": {
    "gutter":20,
    "justify": "start",
    "align": "middle"
  },
  model: {
  },
});
let props: any = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  id: {
    type: String,
    default: "",
  },
});
/** 查询部门下拉树结构 */
const getDeptTree = () => {
  deptTreeSelect().then((response: ResponseConfig) => {
    state.deptOptions = response.data;
  });
};


const getInfo = () => {
  getConfigKey("sys.user.initPassword").then((response: ResponseConfig) => {
    state.initPassword = response.msg;
  });
  getUser(props.id).then((res: ResponseConfig) => {
    formJson.value.model = res.data;
    formJson.value.model.roleIds = res.roleIds;
    formJson.value.model.postIds = res.postIds;
    state.postOptions = res.posts;
    state.roleOptions = res.roles;
    if(!formJson.value.password){
      formJson.value.model.password = state.initPassword;
    }
    formJson.value.model.areaType = itemValue(res.data.areaType);
  });
};
watch(
  () => props.modelValue,
  (val) => {
    dialogVisible.value = val;
    if(props.id&&val){
        getInfo();
        getDeptTree();
    }else if(!props.id&&val){
      getDeptTree();
      formJson.value.model = {
        sex: "1",
      };
         getUser().then(response => {
           state.postOptions = response.posts;
    state.roleOptions = response.roles;
      });
    }
  },
  {
    immediate: true,
  }
);

const handleClose = () => {
  emit("update:modelValue", false);
};
watch(
  () => dialogVisible.value,
  (val) => {
    if (!val) {
      handleClose();
    }
  }
);
</script>

<style scoped lang="scss"></style>
